<?php 
class Authentication_AuthenticationController extends Zend_Controller_Action
{
    /*
     * Action Login
     */
    public function loginAction()
    {
        // If we're already logged in, just redirect  
        if(Zend_Auth::getInstance()->hasIdentity())  
        {  
            $this->_redirect('/');  
        }  
  
        $request = $this->getRequest(); 
  
        $errorMessage = "";  
        if($request->isPost())
        {
            $authAdapter = $this->getAuthAdapter();

            // get the username and password from the form
            $username = $request->getParam('username');
            $password = $request->getParam('password');
            if($username!="" && $password!="")
            {
                // pass to the adapter the submitted username and password
                $authAdapter->setIdentity($username)
                            ->setCredential($password);

                $auth = Zend_Auth::getInstance();
                $result = $auth->authenticate($authAdapter);

                // is the user a valid one?
                if($result->isValid())
                {
                    // all info about this user from the login table
                    // commit only the password, we don't need that
                    $userInfo = $authAdapter->getResultRowObject(null, 'password');

                    // the default storage is a session with namespace Zend_Auth
                    $authStorage = $auth->getStorage();
                    $authStorage->write($userInfo);

                    $this->_redirect('/');
                }
                else
                {
                    $errorMessage = "Tên đăng nhập hoặc Mật khẩu không chính xác.";
                }
            }
        }
        $this->view->errorMessage = $errorMessage;
    }
    /*
     * Action Logout
     */
    public function logoutAction()
    {
        // clear everything - session is cleared also!  
        Zend_Auth::getInstance()->clearIdentity();  
        $this->_redirect('/');  
    }
    
    /*
     * Function Get Auth Adapter
     */
    protected function getAuthAdapter()
    {
        $dbAdapter = Zend_Db_Table::getDefaultAdapter();
        $authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);

        $authAdapter->setTableName('qtht_users')
                    ->setIdentityColumn('USERNAME')
                    ->setCredentialColumn('PASSWORD')
                    ->setCredentialTreatment('MD5(?)');
                    
        return $authAdapter;
    }
}